package com.wp.rcm.config.shiro;

import com.wp.rcm.pojo.User;
import com.wp.rcm.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权。。。。");
        User loginUser  = (User) principalCollection.getPrimaryPrincipal();//身份
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //静态授权：授予主体响应的角色和权限
        info.addRole(loginUser.getRoleName());//角色
        //权限
        info.addStringPermission("用户列表");

        if("管理员".equals(loginUser.getRoleName())){
            info.addStringPermission("用户添加");
            info.addStringPermission("销售机会列表");
            info.addStringPermission("销售新增");
            info.addStringPermission("用户编辑");
        }
//         动态授权
        return info;
    }



    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证");
        //获取用户信息==》token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //方法调用
        String usrName = token.getUsername();
//        String password = token.getPassword();
        User loginUser = userService.findByName(usrName);
        if (loginUser == null) {
            //不存在
            System.out.println("未知的账号异常");
            throw new UnknownAccountException();//未知的账号异常
        }
        if (loginUser.getUsrFlag() != null && loginUser.getUsrFlag().intValue() != 0) {// 账户异常
            //异常
            throw new LockedAccountException();//账号锁定
        }
        //密码校验
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                loginUser, //身份
                loginUser.getUsrPassword(), //凭证
                this.getName()); //realm名称
        return info;
    }
}
